package es.us.lsi.daw.dao.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import es.us.lsi.daw.dao.DAOTwitterMySQL;
import es.us.lsi.daw.dto.DTODatoGrafica;
import es.us.lsi.daw.modelmysql.TweetEntity;

@Component
@Transactional(value = "transactionManagerTweets")
public class DAOTwitterMySQLImpl extends DAOComunImpl implements DAOTwitterMySQL{
	
	public static final Long millisInDay = 86400000L;
	
	@Autowired
	@Qualifier("sessionFactoryTweets")
	protected SessionFactory sessionFactoryTweets;

	public List<DTODatoGrafica> getLstDTODatoGrafica(Long startDate,
			Long endDate){
		Long auxDate = startDate;
		List<DTODatoGrafica> lstDtoDatoGrafica = new ArrayList<DTODatoGrafica>();

		long tTotal = 0L;
		System.out.println("MySQL");
		
		while (auxDate < endDate) {

			Long auxDate2 = auxDate + millisInDay;
			Calendar cldStart = Calendar.getInstance();
			cldStart.setTimeInMillis(auxDate);
			Calendar cldEnd = Calendar.getInstance();
			cldEnd.setTimeInMillis(auxDate2);

			Session session = sessionFactoryTweets.getCurrentSession();
			org.hibernate.Criteria crtTweets = session
					.createCriteria(TweetEntity.class);
			crtTweets.add(Restrictions.between(TweetEntity.A_PUBLISH_DATE,
					cldStart, cldEnd));
			crtTweets.setProjection(Projections.rowCount());
			
			long tInit = System.currentTimeMillis();			
			Long count = (Long) crtTweets.uniqueResult();
			long tEnd1 = System.currentTimeMillis();

			System.out.println(auxDate+";"+auxDate2+";"+count+";"+ (tEnd1 - tInit));
			tTotal += (tEnd1 - tInit);

			DTODatoGrafica dtoDatoGrafica = new DTODatoGrafica();
			dtoDatoGrafica.setDateStart(auxDate);
			dtoDatoGrafica.setDateEnd(auxDate2);
			dtoDatoGrafica.setNumTweets(count);

			auxDate = auxDate2;

			lstDtoDatoGrafica.add(dtoDatoGrafica);
		}

		return lstDtoDatoGrafica;
	}
	
}
